/*
 ********************************************************************************
 *
 * Copyright (c) 2019-2024 Renesas Electronics Corporation and/or its affiliates
 *
 ********************************************************************************
 */

package com.dialog.suotalib.dialogs;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class DialogFragmentManager implements Parcelable {

    protected DialogFragmentManager(Parcel in) {
        dialogType = in.readInt();
        cancelableOnTouchOutside = in.readByte() != 0;
    }

    public static final Creator<DialogFragmentManager> CREATOR = new Creator<DialogFragmentManager>() {
        @Override
        public DialogFragmentManager createFromParcel(Parcel in) {
            return new DialogFragmentManager(in);
        }

        @Override
        public DialogFragmentManager[] newArray(int size) {
            return new DialogFragmentManager[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(dialogType);
        parcel.writeByte((byte) (cancelableOnTouchOutside ? 1 : 0));
    }

    /**
     * Triggered when a custom layout is being used at the dialog instead of the default alert dialog.
     */
    public interface OnViewCreatedListener {
        void onViewCreated(View root);
    }

    /**
     * Implement the following interface to handle interaction with the dialog fragment.
     */
    public interface OnResponseListener {
        void onActionPerformed();
    }

    static final String LAYOUT_KEY = "LAYOUT_KEY";
    static final String TYPE_KEY = "TYPE_KEY";
    static final String CANCELABLE_ON_OUTSIDE_KEY = "CANCELABLE_OUTSIDE_KEY";
    private static final String TITLE_KEY = "TITLE_KEY";
    private static final String MSG_KEY = "MSG_KEY";
    private static final String POSITIVE_KEY = "POSITIVE_KEY";
    private static final String NEGATIVE_KEY = "NEGATIVE_KEY";
    private static final String ICON_KEY = "ICON_KEY";
    private static final String CANCELABLE_KEY = "CANCELABLE_KEY";
    public static final String DIALOG_MANAGER = "MANAGER_KEY";

    private final int dialogType;
    private final boolean cancelableOnTouchOutside;

    private OnViewCreatedListener onViewCreatedListener;
    private OnResponseListener onPositiveClickListener;
    private OnResponseListener onNegativeClickListener;
    private OnResponseListener onDismissListener;
    private OnResponseListener onDialogBackPressedListener;

    int getDialogType() {
        return dialogType;
    }

    boolean isCancelableOnTouchOutside() {
        return cancelableOnTouchOutside;
    }

    DialogFragmentManager(int type, boolean cancelableOnOutside) {
        dialogType = type;
        cancelableOnTouchOutside = cancelableOnOutside;
    }

    void setOnPositiveClickListener(OnResponseListener onPositiveClickListener) {
        this.onPositiveClickListener = onPositiveClickListener;
    }

    void setOnNegativeClickListener(OnResponseListener onNegativeClickListener) {
        this.onNegativeClickListener = onNegativeClickListener;
    }

    void setOnDismissListener(OnResponseListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    void setOnDialogBackPressedListener(OnResponseListener onDialogBackPressedListener) {
        this.onDialogBackPressedListener = onDialogBackPressedListener;
    }

    void setOnViewCreatedListener(OnViewCreatedListener onViewCreatedListener) {
        this.onViewCreatedListener = onViewCreatedListener;
    }

    static Bundle createArgumentsBundle(int type, boolean cancelableOnOutside, int layoutResourceId, boolean cancelable, DialogFragmentManager dialogFragmentManager) {
        Bundle args = new Bundle();
        args.putInt(TYPE_KEY, type);
        args.putBoolean(CANCELABLE_ON_OUTSIDE_KEY, cancelableOnOutside);
        args.putInt(LAYOUT_KEY, layoutResourceId);
        args.putBoolean(CANCELABLE_KEY, cancelable);
        args.putParcelable(DIALOG_MANAGER, dialogFragmentManager);
        return args;
    }

    static Bundle createArgumentsBundle(int type, boolean cancelableOnOutside, @NonNull String title, @NonNull String message, String positive, String negative, int iconResourceId, boolean cancelable, DialogFragmentManager dialogFragmentManager) {
        Bundle args = new Bundle();
        args.putInt(TYPE_KEY, type);
        args.putBoolean(CANCELABLE_ON_OUTSIDE_KEY, cancelableOnOutside);
        args.putString(TITLE_KEY, title);
        args.putString(MSG_KEY, message);
        args.putParcelable(DIALOG_MANAGER, dialogFragmentManager);
        if (!TextUtils.isEmpty(positive))
            args.putString(POSITIVE_KEY, positive);
        if (!TextUtils.isEmpty(negative))
            args.putString(NEGATIVE_KEY, negative);
        if (iconResourceId != -1)
            args.putInt(ICON_KEY, iconResourceId);
        args.putBoolean(CANCELABLE_KEY, cancelable);
        return args;
    }

    void onDismiss() {
        if (onDismissListener != null)
            onDismissListener.onActionPerformed();
    }

    void setCancellation(Dialog dialog, Bundle args) {
        dialog.setCancelable(args.getBoolean(CANCELABLE_KEY));
        dialog.setCanceledOnTouchOutside(cancelableOnTouchOutside);
    }

    boolean onBackPressesListenerHasBeenSet() {
        return onDialogBackPressedListener != null;
    }

    // inflate custom layout to the dialog
    View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, int layoutId) {
        View root = inflater.inflate(layoutId, container);
        if (onViewCreatedListener != null)
            onViewCreatedListener.onViewCreated(root);
        return root;
    }

    AlertDialog onCreateDialog(Bundle args, Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setTitle(args.getString(TITLE_KEY))
                .setMessage(args.getString(MSG_KEY))
                .setPositiveButton(args.containsKey(POSITIVE_KEY) ? args.getString(POSITIVE_KEY) : activity.getString(android.R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (onPositiveClickListener != null)
                            onPositiveClickListener.onActionPerformed();
                    }
                });
        if (args.containsKey(NEGATIVE_KEY)) {
            builder.setNegativeButton(args.getString(NEGATIVE_KEY), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if (onNegativeClickListener != null)
                        onNegativeClickListener.onActionPerformed();
                }
            });
        }
        if (args.getInt(ICON_KEY) != -1)
            builder.setIcon(args.getInt(ICON_KEY));
        builder.setCancelable(args.getBoolean(CANCELABLE_KEY));

        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(cancelableOnTouchOutside);
        return dialog;
    }

    void handleBackPressed(Dialog dialog) {
        if (dialog == null)
            return;

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, android.view.KeyEvent event) {
                if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
                    if (onDialogBackPressedListener != null)
                        onDialogBackPressedListener.onActionPerformed();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    void removeAllListeners() {
        onViewCreatedListener = null;
        onPositiveClickListener = null;
        onNegativeClickListener = null;
        onDismissListener = null;
        onDialogBackPressedListener = null;
    }
}
